package com.leyou.order.util;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.order.config.PayConfig;
import com.leyou.order.enums.OrderStatusEnum;
import com.leyou.order.enums.PayState;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.mapper.OrderStatusMapper;
import com.leyou.order.pojo.OrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class PayHelper {
    @Autowired
    private WXPay wxPay;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderStatusMapper statusMapper;
    @Autowired
    private PayConfig payConfig;

    public String createPayUrl(Long orderId, Long totalPay, String desc) {
        Map<String, String> data = new HashMap<>();
        // 商品描述
        data.put("body", desc);
        // 订单号
        data.put("out_trade_no", orderId.toString());
        //金额，单位是分
        data.put("total_fee", totalPay.toString());
        //调用微信支付的终端IP（乐优商城的IP）
        data.put("spbill_create_ip", "127.0.0.1");
        //回调地址，付款成功后的接口
        data.put("notify_url", payConfig.getNotifyUrl());
        // 交易类型为扫码支付
        data.put("trade_type", "NATIVE");
        //商品id,使用假数据
        data.put("product_id", "1234567");
        //利用微信pay完成下单
        Map<String, String> result = null;
        try {
            result = this.wxPay.unifiedOrder(data);
        } catch (Exception e) {
            log.error("微信下单,WXPAY工具类统一下单unifiedOrder失败,订单号:{}",orderId, e);
            throw new LyException(ExceptionEnum.WEIXIN_PAY_FAIL);
        }
        //解析结果,写业务
        if (WXPayConstants.FAIL.equals(result.get("return_code"))) {
            log.error("微信下单通信失败,原因：{}", result.get("return_msg"));
            throw new LyException(ExceptionEnum.WEIXIN_PAY_FAIL);
        }
        if (WXPayConstants.FAIL.equals(result.get("result_code"))) {
            log.error("微信下单业务失败,错误码：{},错误原因:{}", result.get("error_code"), result.get("error_code_des"));
            throw new LyException(ExceptionEnum.WEIXIN_PAY_FAIL);
        }
        //todo 还要检查有个加密的签名是否和我们自己的签名一致
        return result.get("code_url");
    }

    /**
     * 查询订单状态
     *
     * @param orderId
     * @return
     */
    public PayState queryOrder(Long orderId) {
        Map<String, String> data = new HashMap<>();
        // 订单号
        data.put("out_trade_no", orderId.toString());
        try {
            Map<String, String> result = this.wxPay.orderQuery(data);
            if (result == null) {
                // 未查询到结果，认为是未付款
                return PayState.NOT_PAY;
            }
            //校验状态,校验签名,校验金额 todo 就不写了
            String state = result.get("trade_state");
            if ("SUCCESS".equals(state)) {
                // success，则认为付款成功
                // 修改订单状态
                OrderStatus status = new OrderStatus();
                status.setStatus(OrderStatusEnum.PAYED.value());
                status.setOrderId(orderId);
                status.setPaymentTime(new Date());
                int i = statusMapper.updateByPrimaryKeySelective(status);
                if (i != 1) {
                    throw new LyException(ExceptionEnum.UPDATE_ORDER_STATUS_FAIL);
                }
                return PayState.SUCCESS;
            } else if (StringUtils.equals("USERPAYING", state) || StringUtils.equals("NOTPAY", state)) {
                // 未付款或正在付款，都认为是未付款
                return PayState.NOT_PAY;
            } else {
                // 其它状态认为是付款失败
                return PayState.FAIL;
            }
        } catch (Exception e) {
            log.error("查询订单状态异常", e);
            return PayState.NOT_PAY;
        }
    }
}
